/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  SupervisionDataAnalysisActivity.java   
 * @Package com.jiyi.activity.supervision   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-10-19 下午6:15:59   
 * @version V1.0     
 */
package com.jiyi.activity.supervision;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.XAxis.XAxisPosition;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.google.gson.Gson;
import com.jiyi.bean.supervision.SupervisionDataAnalysisJson;
import com.jiyi.bean.supervision.SupervisionDataAnalysisJson.EquipmentList;
import com.jiyi.bean.supervision.SupervisionDataAnalysisJson.FaultequipmentList;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.inteface.WebApi;
import com.jiyi.view.MyMarkerView;
import com.jiyi.widget.MyTimeAxisValueFormatter;
import com.swift.base.ActivityBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ClassName: SupervisionDataAnalysisActivity
 * @Description:TODO(监管的数据分析)
 * @author: HYM
 * @date: 2017-10-19 下午6:15:59
 * 
 */
public class SupervisionDataAnalysisActivity extends ActivityBase {

	/* 头部 */
	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.tvSearch)
	TextView tvSearch;

	private LayoutInflater inflate;
	@BindView(R.id.gzlBarChart)
	BarChart gzlBarChart;
	@BindView(R.id.gzlPieChart)
	PieChart gzlPieChart;
	List<EquipmentList> gzlTimes = new ArrayList<EquipmentList>();
	List<FaultequipmentList> gzlTop = new ArrayList<FaultequipmentList>();

	@BindView(R.id.tvGzlTotal)
	TextView tvGzlTotal;
	@BindView(R.id.tvGzlTenTotal)
	TextView tvGzlTenTotal;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_supervision_data_analysis);
		ButterKnife.bind(this);
		init();
	}

	private void init() {
		getNewsDate();
		inflate = LayoutInflater.from(this);
		setTop();
		getData();

	}

	private void getNewsDate() {
		Calendar c = Calendar.getInstance();
		int curYear = c.get(Calendar.YEAR);
		tvGzlTotal.setText(curYear+tvGzlTotal.getText().toString());
		tvGzlTenTotal.setText(curYear+tvGzlTenTotal.getText().toString());
	}

	private void setTop() {
		tvTitle.setText("数据分析");
		tvSearch.setVisibility(View.GONE);
	}

	private void getData() {
		String url = "";
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());

		url = WebApi.SUPERVISION_DATA_ANALYSIS;

		VolleyRequest.StringRequestPost(this, url, "", params,
				new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {

								SupervisionDataAnalysisJson temp = new Gson()
										.fromJson(result,
												SupervisionDataAnalysisJson.class);
								gzlTimes.clear();
								gzlTimes.addAll(temp.getData()
										.getEquipmentList());
								gzlTop.clear();
								gzlTop.addAll(temp.getData()
										.getFaultequipmentList());
								if (gzlTimes!= null && gzlTimes.size()>0) {
									generateGZL(gzlTimes);
								}
								if (gzlTop!= null && gzlTop.size()>0) {
									generateGZLTop(gzlTop);
								}

							} else if (status.equals("404")
									&& info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg(
										"尚未登录或该用户在其他地方登录，请重新登录！");
								// 清除环信登录
								UserHelp.getInstance().clearUser(
										AppBase.Context, true);
								return;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
						}
					}

					@Override
					public void stringError(VolleyError error) {
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}

	void generateGZL(List<EquipmentList> temp) {
		gzlBarChart.getDescription().setEnabled(false);
		gzlBarChart.setMaxVisibleValueCount(60);
		gzlBarChart.setPinchZoom(false);
		gzlBarChart.setDragEnabled(false);
		gzlBarChart.setScaleEnabled(false);

		gzlBarChart.setDrawBarShadow(false);
		gzlBarChart.setDrawGridBackground(false);

		XAxis xAxis = gzlBarChart.getXAxis();
		xAxis.setPosition(XAxisPosition.BOTTOM);
		xAxis.setDrawGridLines(false);
		xAxis.setDrawAxisLine(false);

		YAxis rightAxis = gzlBarChart.getAxisRight();
		rightAxis.setEnabled(false);

		IAxisValueFormatter custom = new MyTimeAxisValueFormatter();
		YAxis leftAxis = gzlBarChart.getAxisLeft();
		leftAxis.setLabelCount(5, false);
		leftAxis.setDrawGridLines(false);
		leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
		leftAxis.setDrawAxisLine(false);
		leftAxis.setXOffset(10);
		leftAxis.setGridColor(Color.parseColor("#F5E7CF"));
		leftAxis.setGranularity(1);
		leftAxis.setValueFormatter(custom);

		MyMarkerView mv = new MyMarkerView(this, R.layout.custom_marker_view);
		mv.setChartView(gzlBarChart); // For bounds control
		gzlBarChart.setMarker(mv);

		gzlBarChart.animateY(2500);

		gzlBarChart.getLegend().setEnabled(false);

		// 设置数据
		ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();

		for (int i = 1; i < 13; i++) {
			boolean hasData = false;
			for (int j = 0; j < temp.size(); j++) {
				if (i == temp.get(j).getMonth()) {
					yVals1.add(new BarEntry(i, temp.get(j).getCount()));
					hasData = true;
					break;
				}
			}
			if (!hasData) {
				yVals1.add(new BarEntry(i, 10));
			}
		}

		BarDataSet set1;

		if (gzlBarChart.getData() != null
				&& gzlBarChart.getData().getDataSetCount() > 0) {
			set1 = (BarDataSet) gzlBarChart.getData().getDataSetByIndex(0);
			set1.setValues(yVals1);
			gzlBarChart.getData().notifyDataChanged();
			gzlBarChart.notifyDataSetChanged();
		} else {
			set1 = new BarDataSet(yVals1, "Data Set");
			set1.setColors(ColorTemplate.VORDIPLOM_COLORS);
			set1.setDrawValues(false);

			ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
			dataSets.add(set1);

			BarData data = new BarData(dataSets);
			gzlBarChart.setData(data);
			gzlBarChart.setFitBars(true);
		}

		gzlBarChart.invalidate();
	}

	private void generateGZLTop(List<FaultequipmentList> temp) {

		ArrayList<PieEntry> entries = new ArrayList<PieEntry>();
		ArrayList<Integer> colors = new ArrayList<Integer>();

		for (int i = 0; i < temp.size(); i++) {
			colors.add(getRandColorCode());
			entries.add(new PieEntry((float) (temp.get(i).getCount()), temp
					.get(i).getName()));
		}

		PieDataSet d = new PieDataSet(entries, "");

		// space between slices
		d.setSliceSpace(2f);
		d.setColors(colors);
		// d.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
		// d.setValueLinePart1OffsetPercentage(80.f);
		// d.setValueLinePart1Length(0.2f);
		// d.setValueLinePart2Length(0.4f);

		PieData cd = new PieData(d);
		cd.setValueFormatter(new PercentFormatter());
		gzlPieChart.setBackgroundColor(Color.WHITE);
		gzlPieChart.setUsePercentValues(true);
		gzlPieChart.getDescription().setEnabled(false);

		gzlPieChart.setDrawHoleEnabled(true);
		gzlPieChart.setHoleColor(Color.WHITE);

		gzlPieChart.setTransparentCircleColor(Color.WHITE);
		gzlPieChart.setTransparentCircleAlpha(110);

		gzlPieChart.setHoleRadius(58f);
		gzlPieChart.setTransparentCircleRadius(61f);

		gzlPieChart.setRotationEnabled(true);
		gzlPieChart.setHighlightPerTapEnabled(true);
		// pieChart.setEntryLabelColor(Color.BLACK);
		// pieChart.highlightValue(null);

		// pieChart.setMaxAngle(180f); // HALF CHART
		// pieChart.setRotationAngle(180f);
		gzlPieChart.setDrawSliceText(false);
		Legend mLegend = gzlPieChart.getLegend(); // 设置比例图
		mLegend.setPosition(Legend.LegendPosition.BELOW_CHART_LEFT); // 左下边显示
		mLegend.setFormSize(12f);// 比例块字体大小
		mLegend.setXEntrySpace(2f);// 设置距离饼图的距离，防止与饼图重合
		mLegend.setYEntrySpace(2f);
		// 设置比例块换行...
		mLegend.setWordWrapEnabled(true);
		mLegend.setForm(Legend.LegendForm.SQUARE);// 设置比例块形状，默认为方块
		// do not forget to refresh the chart
		// holder.chart.invalidate();
		// set data
		gzlPieChart.setData(cd);

		gzlPieChart.animateY(900);

	}

	/**
	 * 获取十六进制的颜色代码.例如 "#6E36B4" , For HTML ,
	 * 
	 * @return String
	 */
	public static int getRandColorCode() {
		Random random = new Random();
		int ranColor = 0xff000000 | random.nextInt(0x00ffffff);
		return ranColor;
	}

	@OnClick({ R.id.tvBack })
	public void onClick(View view) {
		Intent intent = null;
		switch (view.getId()) {
		case R.id.tvBack:
			finish();
			break;
		default:
			break;
		}
	}
}
